package com.googlecode.javaeeutils.jpa.manager;

import java.util.List;

import javax.persistence.TypedQuery;

import org.apache.commons.lang.reflect.FieldUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.javaeeutils.jpa.PersistentEntity;

public class EntityFinder {

    private static Logger log = LoggerFactory.getLogger(EntityFinder.class);

    @SuppressWarnings("unchecked")
    public static <ENTITY extends PersistentEntity> ENTITY getSavedEntity(ENTITY entity) {
        if (entity == null) {
            return null;
        }
        if (entity.getId() == null) {
            return entity;
        }
        return (ENTITY) EntityManagerLocator.get().find(entity.getClass(), entity.getId());
    }

    public static <ENTITY extends PersistentEntity> ENTITY findBy(Class<ENTITY> clazz, ENTITY entity, String... keys) {
        String query = "SELECT e FROM " + clazz.getSimpleName() + " e WHERE (1 = 1)";
        for (String key : keys) {
            query = query + " AND " + key + " = :" + key;
        }
        TypedQuery<ENTITY> jpaQuery = EntityManagerLocator.get().createQuery(query, clazz);
        for (String key : keys) {
            try {
                jpaQuery.setParameter(key, FieldUtils.readField(entity, key, true));
            } catch (IllegalAccessException e) {
                log.error("", e);
            }
        }
        List<ENTITY> resultList = jpaQuery.getResultList();
        if (resultList.size() > 1) {
            log.warn("findBy(clazz=" + clazz + ", entity=" + entity + ", keys=" + keys + ") is not unique! Returning " + resultList.get(0));
        }
        if (resultList.isEmpty()) {
            return null;
        }
        return resultList.get(0);
    }

}
